package com.seestech.sell.web.report;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.github.pagehelper.Page;
import com.seestech.sell.common.annotation.RecordLog;
import com.seestech.sell.common.config.ApplicationConfig;
import com.seestech.sell.common.utils.*;
import com.seestech.sell.domain.model.CompanyPay;
import com.seestech.sell.domain.model.Order;
import com.seestech.sell.domain.model.Refund;
import com.seestech.sell.domain.model.User;
import com.seestech.sell.domain.model.pay.WeichatRefundResult;
import com.seestech.sell.service.ICompanyPayService;
import com.seestech.sell.service.IOrderService;
import com.seestech.sell.service.IRefundService;
import com.seestech.sell.service.pay.AlipayService;
import com.seestech.sell.service.pay.WeichatPayService;
import com.seestech.sell.web.SuperController;
import org.apache.ibatis.session.RowBounds;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by idiot on 2017/6/22.
 */
@Controller
@RequestMapping(value = "refund")
public class RefundController extends SuperController {
    private static Logger logger = LoggerFactory.getLogger(RefundController.class);

    @Resource
    private IRefundService refundService;
    @Resource
    private WeichatPayService weichatPayService;
    @Resource
    private AlipayService alipayService;
    @Resource
    private ApplicationConfig applicationConfig;
    @Resource
    private IOrderService orderService;
    @Resource
    private ICompanyPayService companyPayService;
    @Resource
    private RestTemplate restTemplate;

    //加载page页面
    @RequiresPermissions(value = "refund:page")
    @RequestMapping(value = "page", method = RequestMethod.GET)
    public String toPage(Model model){
        logger.info("加载退款页面信息=====》》》");
        return "refund/page";
    }

    //加载data页面
    @RequestMapping(value = "data", method = RequestMethod.POST)
    public String data(Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize, Refund info, Model model){
        User user = getUser();
        if(user == null){
            logger.error("加载退款数据页面======>>>>>>>>用户信息失效，请重新登录");
            return "login";
        }
        List<Long> companyIds = getCompanyIdsByUser(user);
        info.setCompanyIds(companyIds);
        Page<Refund> lists = refundService.getAllRefundes(new RowBounds((pageNo-1)*pageSize, pageSize), info);
        model.addAttribute("lists", lists);
        return "refund/data";
    }

    //修改
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public void update(Refund info){
        User user = getUser();
        if (user == null){
            ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "用户信息已经失效，请重新登录");
            return;
        }
        // 根据订单编号 关联企业信息   加载企业支付配置信息
        CompanyPay companyPay = companyPayService.getCompanyPayByOrderId(info.getOrderId());
        if (companyPay == null){
            ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "企业支付配置不存在");
            return;
        }
        //根据订单编号获取订单信息
        Order order = orderService.getOrderByOrderId(info.getOrderId());
        if(order == null){
            logger.error("手动退款请求==============>>>>>无效的参数orderId");
            ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "无效的订单信息");
            return;
        }
        // 判断企业支付配置 中的微信或者支付宝是否开启  没开启返回错误提示信息
        if (companyPay != null && (
                (companyPay.getOpenWechatPay()== null || companyPay.getOpenWechatPay() == 0)
                && (companyPay.getOpenAlipay() == null || companyPay.getOpenAlipay() == 0)
                && (companyPay.getOpenCodePay() == null || companyPay.getOpenCodePay() == 0))){
            ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "企业支付配置未开启");
            return;
        }
        if(info.getRefundId() == null){
            info.setCreateUser(getUser().getUserId());  //设置创建人
            Long refundId = IdGen.get().nextId();
            info.setRefundId(refundId);     //设置主键
            // 微信退款   检测是否开启微信退款
            if(info.getChannel() == 1 && companyPay.getOpenWechatPay() == 1){
                //微信退款
                logger.info("微信退款请求==================>>>>>>>>>>>>开始");
                String certPath = FileUtils.getWindowsPath(FileUtils.addPathSeparate(applicationConfig.getBaseDirectory(),
                        companyPay.getWechatCertPath()));
                WeichatRefundResult result = weichatPayService.refundResult(companyPay.getWechatAppId(),
                        companyPay.getWechatMchId(), companyPay.getWechatMchKey(), String.valueOf(refundId),
                        String.valueOf(info.getOrderId()), info.getTotalFee(), info.getRefundFee(), certPath);
                if("SUCCESS".equals(result.getReturn_code()) && "SUCCESS".equals(result.getResult_code())){
                    info.setSuccess(1);     //微信退款成功
                    updateOrder(info.getOrderId()); //修改订单信息
                }else {
                    info.setSuccess(0);
                    logger.error("微信退款请求==>>失败===>>>>"+result.getReturn_msg());
                }
                logger.info("微信退款请求==================>>>>>>>>>>>>结束");
            }else if(info.getChannel() == 2 && companyPay.getOpenAlipay() == 1){     // 支付宝退款  检测是否开启支付宝退款
                //支付宝退款
                logger.info("支付宝退款请求==================>>>>>>>>>>>>开始");
                AlipayTradeRefundResponse result = null;
                try {
                    result = alipayService.refundResponse(companyPay.getAlipayAppId(), companyPay.getAlipayPublicKey(),
                            companyPay.getAlipayPrivateKey(), companyPay.getAlipaySignType(),
                            String.valueOf(info.getOrderId()), info.getRefundFee(), info.getReason());
                } catch (AlipayApiException e) {
                    logger.error("支付宝申请退款失败。错误原因："+e.getMessage());
                    info.setSuccess(0);
                }
                if(result != null && "10000".equals(result.getCode())){
                    info.setSuccess(1);     //支付宝退款成功
                    updateOrder(info.getOrderId()); //修改订单信息
                }else {
                    logger.error("支付宝退款请求==>>失败===>>>>");
                    if (result != null)
                        logger.error("失败原因===>>>>"+result.getMsg());
                    info.setSuccess(0);
                }
                logger.info("支付宝退款请求==================>>>>>>>>>>>>结束");
            }else if(info.getChannel() == 3 && companyPay.getOpenCodePay() == 1) {     // 积分退款  检测是否开启积分退款
                logger.info("积分退款请求==================>>>>>>>>>>>>开始");
                long time = System.currentTimeMillis()/1000;
                String initCode = order.getCardId() + order.getOrderNumber() + (time-9999);
                String code = EncodeMD5.GetMD5Code(new StringBuffer(initCode).reverse().toString());
                //发起退积分请求  获取返回结果
                JSONObject jsonObject = new JSONObject();
                MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
                paramMap.add("card_id", order.getCardId());
                paramMap.add("order_number", order.getOrderNumber());
                paramMap.add("time", time);
                paramMap.add("code", code);
                jsonObject = restTemplate.postForObject(companyPay.getCodeRefundUrl(), paramMap, JSONObject.class);
                if ("success".equals(jsonObject.getString("status"))){
                    info.setSuccess(1);     //积分退款成功
                    updateOrder(info.getOrderId()); //修改订单信息
                }else {
                    logger.error("积分退款请求==>>失败===>>>>");
                    info.setSuccess(0);
                }
                logger.info("积分退款请求==================>>>>>>>>>>>>结束");
            }else {
                info.setSuccess(0);
            }
            refundService.insert(info);         //新增
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "申请退款成功");
        }else {
            ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "申请退款失败");
        }
    }


    //删除品牌信息
    @RecordLog(value = "删除订单信息")
    @RequestMapping(value = "{refundId}/delete", method = RequestMethod.POST)
    public void delete(@PathVariable("refundId") Long refundId){
        refundService.delete(refundId);
        ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(),"删除退款信息成功");
    }

    //批量删除
    @RequestMapping(value = "deleteBatch", method = RequestMethod.POST)
    public void deleteBatch(@RequestParam("ids[]") Long[] refundIds){
        refundService.deleteBatch(refundIds);
        ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(),"批量删除退款信息成功");
    }


    //修改订单信息
    private void updateOrder(Long orderId){
        Order order = orderService.getOrderByOrderId(orderId);
        if (order != null){
            order.setSuccess(2);        //更改为退款
            orderService.update(order);
        }
    }

}
